import { computed, ref } from 'vue'
import { defineStore } from 'pinia'
const useUserStore = defineStore('user', () => {
  const user = ref({})
  const userActiveIndex = ref('/user/userInfo')
  const name = computed(() => {
    return (
      user.value?.payload?.user?.name || user.value?.payload?.user?.username
    )
  })

  const token = computed(() => user.value?.payload?.token?.token)

  const logged = computed(() => {
    var createdAt = user.value?.payload?.token?.createdAt
    return createdAt && Date.parse(createdAt) + 2 * 3600 * 1000 > Date.now()
  })

  const allow = authority =>
    user.value?.payload?.authorities.includes(authority)

  const load = () => {
    user.value = JSON.parse(window.localStorage.getItem('user'))
  }

  const login = data => {
    user.value = data
    window.localStorage.setItem('user', JSON.stringify(data))
  }

  const logout = () => {
    user.value = null
    window.localStorage.removeItem('user')
  }

  const isAdmin = () => {
    if (user.value.payload.user.roleId == 2) {
      return true
    }
    return false
  }

  const isExpert = () => {
    // console.log(user.value.payload.user.roleId)

    if (user.value.payload.user.roleId == 3) {
      return true
    }
    return false
  }
  const setUser = (users) => {
    user.value = users
  }

  return {
    user,
    name,
    token,
    logged,
    userActiveIndex,
    allow,
    load,
    login,
    logout,
    isAdmin,
    isExpert,
    setUser,
  }
})

export default useUserStore
